//
//  BBZoomView.m
//  xNose
//
//  Created by ben smith on 16/09/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BBZoomView.h"
#import "BBNodeController.h"


@implementation BBZoomView

@synthesize scrollX;
@synthesize scrollWidth;

@synthesize connections;
@synthesize highlight;

@synthesize mainImage;
@synthesize overlayImage;
@synthesize highlightImage;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
			connections = NO;
			highlight = NO;
			[self activate];
    }
    return self;
}

-(void)activate
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toggleConnectedNotification:) name:@"BBToggleConnected" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(highlightConnectedNotification:) name:@"BBHighlightConnected" object:nil];
}

-(void)deactivate
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)toggleConnectedNotification:(id)sender
{
	connections = !connections;
	[self setNeedsDisplay:YES];
}

-(void)highlightConnectedNotification:(id)sender
{
	highlight = !highlight;
	[self setNeedsDisplay:YES];
}


- (void)drawRect:(NSRect)rect {
    // Drawing code here.
	NSSize size = [mainImage size];
	float ratio = NSWidth([self bounds])/size.width;
	size.height *= ratio;
	size.width *= ratio;
	NSRect drawRect = NSMakeRect(0, NSMidY([self bounds]) - size.height/2.0, size.width, size.height);
	[mainImage drawInRect:drawRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

	if (highlight) {
		[[NSColor colorWithDeviceWhite:0.0 alpha:0.5] set];
		[NSBezierPath fillRect:[self bounds]];
		[highlightImage drawInRect:drawRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
		return;
	}
	
	if (connections) [overlayImage drawInRect:drawRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
}


-(void)mouseDown:(NSEvent*)theEvent
{
	NSPoint mouseDown = [[[self window] contentView] convertPoint:[theEvent locationInWindow] toView:self];
	// make a new scrollpoint
	float ratio = mouseDown.x/NSWidth([self bounds]);
	float mouseDownScrollValue = scrollWidth * ratio;
	float newScroll = mouseDownScrollValue + scrollX - (NSWidth([self bounds]) / 2.0);
	[[BBNodeController sharedNodeController] zoomNotification:[NSNumber numberWithFloat:-newScroll]];
}

-(void)mouseDragged:(NSEvent*)theEvent
{
	
}

-(void)mouseUp:(NSEvent*)theEvent
{
	
}


-(void)otherMouseDown:(NSEvent*)theEvent
{
	[self mouseDown:theEvent];
}

-(void)otherMouseUp:(NSEvent*)theEvent
{
}

-(void)otherMouseDragged:(NSEvent*)theEvent
{
	
}

- (void) dealloc
{
	[self deactivate];
	self.mainImage = nil;
	self.overlayImage = nil;
	self.highlightImage = nil;
	[super dealloc];
}


@end
